package crypto

import (
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server_attence/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strings"
)

// GetPublicKey 获取公钥
func GetPublicKey(c *gin.Context) {
	req := entity.ReqPublicKey{}
	if err := c.ShouldBindQuery(&req); err != nil {
		global.Log.Error("GetPublicKey ShouldBindQuery fail", zap.Any("err", err))
		c.JSON(http.StatusOK, model.Fail("参数错误"))
		return
	}
	// 小写化处理
	cryptoInst, ok := global.Crypto.Asymmetric[strings.ToLower(req.Type)]
	if !ok {
		global.Log.Error("GetPublicKey ShouldBindQuery invalid crypto", zap.Any("type", req.Type))
		c.JSON(http.StatusOK, model.Fail("参数错误"))
		return
	}
	publicKey, err := cryptoInst.GeneratePublicKey(string(global.ASymmetricPrivateKey))
	if err != nil {
		global.Log.Error("GetPublicKey GeneratePublicKey fail", zap.Any("err", err))
		c.JSON(http.StatusOK, model.Fail("获取公钥失败"))
		return
	}
	rsp := entity.RspPublicKey{
		Type:      req.Type,
		PublicKey: publicKey,
	}
	c.JSON(http.StatusOK, model.SuccessObject("操作成功", rsp))
}
